package com.duan.laugh.auth.endpoint;

import com.duan.laugh.common.security.util.LaughUser;
import com.duan.laugh.common.security.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author duanjw
 */
@Slf4j
@RestController
@RequestMapping
public class AuthEndpoint {
    @Autowired
    private AuthenticationManager authenticationManager;

    @GetMapping("tenant")
    public void switchTenant(Authentication authentication) {
        final LaughUser user = UserUtils.getUser();
        log.info(",user:{}", user);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(new String[]{"从数据库中查询出来"});
        SecurityContext context = SecurityContextHolder.getContext();
        LaughUser userDetails = (LaughUser) context.getAuthentication().getPrincipal();
        Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), authorityList);
        //重新设置上下文中存储的用户权限
        context.setAuthentication(auth);
//        authenticationManager.authenticate(authentication);
        log.info("auth:{}", auth);
    }
}
